import React, { useState } from "react";
import { withRouter } from "react-router-dom";
import { doPost } from "../../utils/upload";
import { checkPwdFormat } from "../../utils/format";
import styles from "./index.module.scss";
import { pageIndex, pages } from "../../common/routerConfig";
import URL from "../../common/urls";

const ERR_HINT = "两次输入的密码不一致，请重试:)";
const NULL_HINT = "密码不能为空";
const FORMAT_HINT = "密码长度6~10位\r\n需包含数字、大小写字母";

// 设置密码的界面
const Index = (props) => {
  const { history } = props;
  const { firstSet } = props.location.query || { firstSet: true };
  const [pwd1, setPwd1] = useState("");
  const [pwd2, setPwd2] = useState("");
  const [hint, setHint] = useState("");

  const onChange1 = (e) => {
    const pwd = e.target.value;
    setPwd1((pre) => pwd);
  };

  const onChange2 = (e) => {
    const pwd = e.target.value;
    setPwd2((pre) => pwd);
  };

  const onClick1 = () => {
    setHint((h) => "");
  };

  const onClick2 = () => {
    if (!checkPwdFormat(pwd1)) {
      setHint((h) => FORMAT_HINT);
    }
  };

  const onSubmit = () => {
    if (!checkPwdFormat(pwd1)) {
      setHint((h) => FORMAT_HINT);
    } else if (pwd1 !== pwd2) {
      setHint((h) => ERR_HINT);
    } else if (pwd1 === "") {
      setHint((h) => NULL_HINT);
    }
    // 提交密码
    else {
      setHint((p) => "");
      doPost(URL.doSavePwd, { pwd: pwd1 })
        .then(async (r) => {
          const data = await r.json();
          history.push(pages[pageIndex.home].path);
        })
        .catch((err) => {
          alert(err);
        });
    }
  };

  const onBack = () => {
    history.push(pages[pageIndex.home].path);
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>Set Password</div>
      <div className={styles.inputWrapper}>
        <div className={styles.borderWrapper}>
          <input
            type="password"
            className={styles.borderItem}
            placeholder="新密码"
            onChange={onChange1}
            onClick={onClick1}
          />
        </div>
      </div>
      <div className={styles.inputWrapper}>
        <div className={styles.borderWrapper}>
          <input
            type="password"
            className={styles.borderItem}
            placeholder="再次确认密码"
            onChange={onChange2}
            onClick={onClick2}
          />
        </div>
      </div>
      <div className={styles.hint}>{hint}</div>
      <div className={styles.action}>
        {firstSet ? null : (
          <div className={styles.btn} onClick={onBack}>
            👈cancel
          </div>
        )}
        <div className={styles.btn} onClick={onSubmit}>
          👌submit
        </div>
      </div>
    </div>
  );
};

export default withRouter(Index);
